$(function() {

    function initTab(pageNum, pageSize) {
        $('#pCreate').siblings().remove();
        pageNum = pageNum && pageNum > 0 ? pageNum : 1;
        pageSize = pageSize && pageSize > 0 ? pageSize : 10;
        $.post('/project/page', { pageSize: pageSize, pageNum: pageNum }, function(data) {
            if (data && data.retCode == 0) {
                var page = data.retVal;
                var proList = page.list;
                var html = '';
                var proInfo;
                for (var i = 0; i < proList.length; i++) {
                    proInfo = proList[i];
                    html += renderProjectHtml(proInfo);
                }
                $('#projects').prepend(html);
                $('#projects').attr({
                    pageSize: pageSize,
                    pageNum: pageNum,
                    pages: page.pages
                });
            }
        });
    }

    /**
     * 渲染单个项目html
     *
     * @param      {<type>}  proInfo  The pro information
     * @return     {string}  { description_of_the_return_value }
     */
    function renderProjectHtml(proInfo) {
        var html = '';
        var user = sessionStorage.getItem("account");
        if (proInfo) {
            html += '<div name="project-info" proId="' + proInfo.id + '" class="col-xs-12 col-sm-6 col-md-4 col-lg-3">' +
                '<div class="panel panel-default">' +
                '<div id="pManage" class="p-manage">';
            html += '<div name="project-manager" proId="' + proInfo.id + '"><span name="info" title="详情" class="glyphicon glyphicon-info-sign" aria-hidden="true" style="font-size: 15px;"></span>';
            if (user == proInfo.creator) {
                html += '&nbsp;&nbsp;<span name="transfer" title="权限转让" class="glyphicon glyphicon-transfer" aria-hidden="true" style="font-size: 15px;"></span>' +
                    '&nbsp;&nbsp;<span name="upd" title="修改" class="glyphicon glyphicon-cog" aria-hidden="true" style="font-size: 15px;"></span>' +
                    '&nbsp;&nbsp;<span name="del" title="删除" class="glyphicon glyphicon-remove" aria-hidden="true" style="font-size: 15px;"></span>';
            }
            html += '</div></div>';
            html += '<div class="panel-body" proId="'+proInfo.id+'" title="' + proInfo.description + '">';
            html += proInfo.name;
            html += ' </div></div></div>';
        }
        return html;
    }

    initTab();

    //新增
    $("#pCreate").click(function(event) {
        //准备数据
        $("#updIdInput").val('');
        //打开对话框
        $('#create-modal').modal('show');
        if ('update' == $('#create-modal').attr('type')) {
            createReset();
        }
        $('#create-modal').attr({ "type": "create" });
        $(".modal-title").text('新增');
    });

    $('#createSave').click(function(event) {
        if (checkForm()) {
            var proObj = {
                id: $("#updIdInput").val(),
                name: $('#name').val(),
                tag: $('#tag').val(),
                description: $('#description').val(),
                userIds: $('#userTags').val()
            };
            if (proObj.id > 0) {
                $.post('/project/update', proObj, function(data, textStatus, xhr) {
                    if (data && data.retCode == 0) {
                        $('#create-modal').modal('hide');
                        createReset();
                        $('div[name="project-info"][proId="' + proObj.id + '"] .panel-body')
                            .attr({ 'title': proObj.description })
                            .text(proObj.name);
                        //initTab();
                    }
                });
            } else {
                $.post('/project/create', proObj, function(data, textStatus, xhr) {
                    if (data && data.retCode == 0) {
                        $('#create-modal').modal('hide');
                        createReset();
                        proObj.id = data.retVal;
                        proObj.creator = sessionStorage.getItem("account");
                        $('#projects').prepend(renderProjectHtml(proObj));
                        //initTab();
                    }
                });
            }
        } else {
            //TODO
        }
    });

    $('#createReset').click(function(event) {
        createReset();
    });

    function createReset() {
        $("#createHideRest").click();
        $('#tag').tagsinput('removeAll');
        $('#userTags').tagsinput('removeAll');
    }

    function checkForm() {
        var name = $('#name').val();
        if (null == name || name == 'undefined' || name == '') {
            return fasle;
        }
        return true;
    }

    //点击项目进入文档管理界面
    $('.panels').on('click', 'div[name="project-info"] .panel-body', function(e) {
        // 点击进入文档列表管理界面
        window.location.href = "/static/html/doc/manager.html?projectId=" + $(this).attr('proId') + '&projectName=' + encodeURI($(this).text().trim());
    });

    //项目详情
    $('.panels').on('click', 'div[name="project-info"] span[name="info"]', function(e) {
        var id = $(this).parent().attr("proId");
        showInfo(id);
        // 等效return false; 阻止事件冒泡
        e.stopPropagation();
    });

    //权限转让
    $('.panels').on('click', 'div[name="project-info"] span[name="transfer"]', function(e) {
        var id = $(this).parent().attr('proId');
        $("#transferTip").hide();
        $('#oldCreator').text(sessionStorage.getItem('account'));
        $('#transferIdInput').val(id);
        $('#newCreator').tagsinput('removeAll');
        $('#newCreator').val('');
        //打开对话框
        $('#transfer-modal').modal('show');
        $('#newCreator').tagsinput('focus');
        e.stopPropagation();
    });

    // 更新
    $('.panels').on('click', 'div[name="project-info"] span[name="upd"]', function(e) {
        createReset();
        var id = $(this).parent().attr("proId");
        // 准备数据
        $.get("/project/get/" + id, function(data) {
            if (data && data.retCode == 0) {
                var proInfo = data.retVal;
                $("#updIdInput").val(proInfo.id);
                $('#name').val(proInfo.name);
                $('#description').val(proInfo.description);
                if (proInfo.tag) {
                    proInfo.tag.split(",").forEach(function(element, index) {
                        $('#tag').tagsinput('add', element);
                    });
                }
                if (proInfo.users) {
                    proInfo.users.forEach(function(e, index) {
                        if (e) {
                            $('#userTags').tagsinput('add', { 'id': e.id, 'account': e.account, 'name': e.name == null ? e.account : e.name + '(' + e.account + ')' });
                        }
                    });
                }
            }
        });
        //打开对话框
        $('#create-modal').modal('show');
        $('#create-modal').attr({ "type": "update" });
        $(".modal-title").text('修改');
        e.stopPropagation();
    });

    // 删除
    $('.panels').on('click', 'div[name="project-info"] span[name="del"]', function(e) {
        var self = $(this).parent();
        $.get('/project/delete/' + self.attr('proId'), function(data) {
            if (data && data.retCode == 0) {
                self.parents('div[name="project-info"]').remove();
            }
        });
        e.stopPropagation();
    });

    //权限转让，搜索新用户控件
    $('#transferSave').click(function(event) {
        // 限制转一个用户
        var val = $('#newCreator').tagsinput('items')[0];
        var param = {
            projectId: $('#transferIdInput').val(),
            newOwnerId: val.id
        }
        if (val.account == sessionStorage.getItem('account')) {
            $("#transferTipContent").text('修改无变更');
            $("#transferTip").show();
            return false;
        }
        if (param && param.projectId > 0 && param.newOwnerId > 0) {
            $.post('/project/updateOwner', param, function(data) {
                if (data && data.retCode == 0) {
                    $('#transfer-modal').modal('hide');
                    // 为了去除&nbsp;
                    //$('div[name="project-manager"][proId="' + param.projectId + '"]').children().remove('span[name!="info"]');
                    var manager = $('div[name="project-manager"][proId="' + param.projectId + '"]');
                    var info = manager.children('span[name="info"]');
                    manager.empty().html(info);

                }
            });
            $('#transfer-modal').modal('hide');
        } else {
            $("#transferTipContent").text('参数错误');
            $("#transferTip").show();
        }
    });

    function showInfo(id) {
        //清理数据
        $('#detailName').text('');
        $('#detailTag').html('');
        $('#detailDesc').text('');
        $('#detailCreator').html('');
        $('#detailUsers').html('');
        // 准备数据
        $.get("/project/get/" + id, function(data) {
            if (data && data.retCode == 0) {
                var proInfo = data.retVal;
                $('#detailName').text(proInfo.name);
                $('#detailDesc').text(proInfo.description);
                $('#detailCreator').html('<span class="badge badge-info badge-blue">' + proInfo.creator + '</span>');
                var html = "";
                if (proInfo.tag) {
                    proInfo.tag.split(",").forEach(function(e, index) {
                        html += '<span class="label label-success">' + e + '</span>&nbsp;';
                    });
                    $('#detailTag').html(html);
                }
                if (proInfo.users) {
                    html = '';
                    proInfo.users.forEach(function(e, index) {
                        html += e ? '<span class="badge badge-info badge-blue">' +
                            (e.name == null || '' == e.name ? e.account : e.name) +
                            '</span>&nbsp;' : '';
                    });
                    $('#detailUsers').html(html);
                }
            }
        });
        //打开对话框
        $('#detail-modal').modal('show');
    }

    var usersBH = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: '/user/queryByNameOrAccount?condition=%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var users = new Array();
                    if (data.retVal) {
                        data.retVal.forEach(function(obj) {
                            users.push({
                                'id': obj.id,
                                'name': obj.name == null ? obj.account : obj.name + '(' + obj.account + ')',
                                'account': obj.account
                            });
                        });
                    }
                    return users;
                }
            }
        },
        remote: {
            url: '/user/queryByNameOrAccount?condition=%QUERY',
            wildcard: '%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var users = new Array();
                    if (data.retVal) {
                        data.retVal.forEach(function(obj) {
                            users.push({
                                'id': obj.id,
                                'name': obj.name == null ? obj.account : obj.name + '(' + obj.account + ')',
                                'account': obj.account
                            });
                        });
                    }
                    return users;
                }
            }
        }
    });

    usersBH.initialize();

    /**
     * 权限转移，成员控件初始化。
     */
    $('#newCreator').tagsinput({
        tagClass: function(item) {
            return (item.length > 10 ? 'big' : 'small') + ' badge badge-info badge-blue label label-warning';
        },
        itemValue: 'id',
        itemText: 'name',
        autoSelect: false,
        maxTags: 1,
        typeaheadjs: {
            classNames: { input: 'Typeahead-input' },
            name: 'users',
            value: 'id',
            display: 'name',
            source: usersBH.ttAdapter()
        }
    });

    /**
     * 成员管理:新增修改时使用
     */
    $('#userTags').tagsinput({
        tagClass: function(item) {
            return (item.length > 10 ? 'big' : 'small') + ' badge badge-info badge-blue label label-warning';
        },
        itemValue: 'id',
        itemText: 'name',
        autoSelect: true,
        //freeInput: true,
        typeaheadjs: {
            classNames: { input: 'Typeahead-input' },
            name: 'users',
            value: 'id',
            display: 'name',
            source: usersBH.ttAdapter()
        }
    });

    /**
     * .tt-input 为tagsinput添加的input,当选择数据时，size被设置为placeholder的length，
     * length长度非字节长度因此需要重置size。
     * 如果仅仅监听tagsinput的事件(例:beforeItemAdd),在Dw Arrow，Up Arrow回车选择的时候
     * 并未触发tagsinput的事件，因此都监听。
     * 
     * 方法二：
     * 修改bootstrap-tagsinput.js
     * inputSize = Math.max(1, this.placeholderText.length); 
     * Math.max(this.inputSize, $input.val().length);
     */
    /*$("#newCreator,#userTags").parent().on('keydown', '.tt-input', function() {
        $(this).attr('size', getByteLength($(this).attr('placeholder')));
    });
    $("#newCreator,#userTags").parent().on('beforeItemAdd itemRemoved ', function() {
        var self = $('.tt-input');
        self.attr('size', getByteLength(self.attr('placeholder')));
    });*/

});